﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Serenity;
using WaterCloud.Code;
using WaterCloud.Domain.SystemSecurity;
using WaterCloud.Domain.BasicData;
using WaterCloud.Service;
using WaterCloud.Service.SystemSecurity;
using Microsoft.AspNetCore.Authorization;
using WaterCloud.Service.BasicData;

namespace WaterCloud.Web.Areas.BasicData.Controllers
{
    /// <summary>
    /// 创 建：超级管理员
    /// 日 期：2020-07-04 15:24
    /// 描 述：资产分类2控制器类
    /// </summary>
    [Area("BasicData")]
    public class EquipmentsController :  ControllerBase
    {
        private string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName.Split('.')[5];
        public LogService _logService {get;set;}
        public EquipmentsService _service {get;set;}

        #region 获取数据

        [HttpGet]
        [HandlerAjaxOnly]
        public async Task<ActionResult> GetListJson(string keyValue, string keyword)
        {
            var data = await _service.GetLookList();
            var result = new List<EquipmentsEntity>();
            if (string.IsNullOrEmpty(keyValue))
            {
                keyValue = "0";
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                result = data.TreeWhere(t => t.F_Name.Contains(keyword));
            }
            else
            {
                result = data;
            }
            result = result.Where(t => t.F_ParentCode == keyValue).ToList();
            foreach (var item in result)
            {
                item.haveChild = data.Where(a => a.F_ParentCode == item.F_Code).Count() > 0 ? true : false;
            }
            return Success(data.Count, result);
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public async Task<ActionResult> GetTreeSelectJson(string ParentCode)
        {
            var data = await _service.GetList();
            //默认三级区域
            data = data.Where(a => a.F_Level <3).ToList();
            if (!string.IsNullOrEmpty(ParentCode))
            {
                data = data.Where(a => a.F_HierarchyCode== ParentCode|| a.F_ParentHierarchyCode == ParentCode).ToList();
            }
            var treeList = new List<TreeSelectModel>();
            foreach (EquipmentsEntity item in data)
            {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.F_Code;
                treeModel.text = item.F_Name;
                treeModel.parentId = item.F_ParentCode;
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeSelectJson());
        }
        [HttpGet]
        [HandlerAjaxOnly]
        public async Task<ActionResult> GetGridJson(Pagination pagination, string keyword)
        {
            //此处需修改
            pagination.order = "desc";
            pagination.sort = "F_CreatorTime";
            var data = await _service.GetLookList(pagination,keyword);
            return Success(pagination.records, data);
        }


        [HttpGet]
        [HandlerAjaxOnly]
        public async Task<ActionResult> GetFormJson(string keyValue)
        {
            var data = await _service.GetForm(keyValue);
            return Content(data.ToJson());
        }
        #endregion

        #region 提交数据
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> SubmitForm(EquipmentsEntity entity, string keyValue)
        {
            LogEntity logEntity;
            if (string.IsNullOrEmpty(keyValue))
            {
                logEntity = await _logService.CreateLog(className, DbLogType.Create.ToString());
                logEntity.F_Description += DbLogType.Create.ToDescription();
                //entity.F_DeleteMark = false;
            }
            else
            {
                logEntity = await _logService.CreateLog(className, DbLogType.Update.ToString());
                logEntity.F_Description += DbLogType.Update.ToDescription();
                logEntity.F_KeyValue = keyValue;
            }
            try
            {
                logEntity.F_Account = OperatorProvider.Provider.GetCurrent().UserCode;
                logEntity.F_NickName = OperatorProvider.Provider.GetCurrent().UserName;
                await _service.SubmitForm(entity, keyValue);
                logEntity.F_Description += "操作成功";
                await _logService.WriteDbLog(logEntity);
                return Success("操作成功。");
            }
            catch (Exception ex)
            {
                logEntity.F_Result = false;
                logEntity.F_Description += "操作失败，" + ex.Message;
                await _logService.WriteDbLog(logEntity);
                return Error(ex.Message);
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ServiceFilter(typeof(HandlerAuthorizeAttribute))]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteForm(string keyValue)
        {
            LogEntity logEntity = await _logService.CreateLog(className, DbLogType.Delete.ToString());
            logEntity.F_Description += DbLogType.Delete.ToDescription();
            try
            {
                logEntity.F_Account = OperatorProvider.Provider.GetCurrent().UserCode;
                logEntity.F_NickName = OperatorProvider.Provider.GetCurrent().UserName;
                await _service.DeleteForm(keyValue);
                logEntity.F_Description += "操作成功";
                await _logService.WriteDbLog(logEntity);
                return Success("操作成功。");
            }
            catch (Exception ex)
            {
                logEntity.F_Result = false;
                logEntity.F_Description += "操作失败，" + ex.Message;
                await _logService.WriteDbLog(logEntity);
                return Error(ex.Message);
            }
        }
        #endregion
    }
}
